package com.chuan.demo02;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//线程创建：实现Callable接口
public class TestCallable implements Callable<Boolean> {
    private String url;
    private String name;
    public TestCallable(String url, String name){
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("文件名："+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://img2.baidu.com/it/u=3150567454,1089677718&fm=253&fmt=auto&app=138&f=PNG?w=600&h=369","1.jpg");
        TestCallable t2 = new TestCallable("https://img1.baidu.com/it/u=470255208,2889809727&fm=253&fmt=auto&app=120&f=JPEG?w=950&h=443","2.jpg");
        TestCallable t3 = new TestCallable("https://img1.baidu.com/it/u=1503222636,2429859130&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500","3.jpg");
        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        //获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();
        //关闭服务
        ser.shutdownNow();
    }
}
//下载器
class WebDownloader{
    public void downloader(String url, String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO downloader方法异常");
        }
    }
}